package com.co0964.fetcher;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import com.co0964.Main;
import com.co0964.bean.Category;

public class CategoryFetcher {
	
	private HttpClient client = new HttpClient();
	
	
	public List<Category> fetch(){
		PostMethod getMethod = null;
		try{
			getMethod = new PostMethod("http://0964.co.kr/");
			getMethod.addRequestHeader("Cookie", Main.COOKIE);
			client.executeMethod(getMethod);
			String result = getMethod.getResponseBodyAsString();
			return parse(result);
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			getMethod.releaseConnection();
		}
		return null;
	}
	
	
	private List<Category> parse(String content){
		List<Category> list = new ArrayList<Category>();
		Matcher matcher = Pattern.compile("href=\"/front/php/category.php\\?cate_no=(\\d+?)\"").matcher(content);
		while(matcher.find()){
			Category category = new Category();
			category.setCid(Integer.parseInt(matcher.group(1)));
			list.add(category);
			System.out.println(category.getCid());
		}
		
		return list;
	}
	
	
	public void close(){
		try{
			client.getHttpConnectionManager().closeIdleConnections(0);
		}catch (Exception e) {
		}
	}
}
